<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Entity\UserFacebook;
use Application\Entity\User;
use Zend\Mvc\Controller\Plugin\Redirect;
use Zend\Authentication\AuthenticationService;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;
use Zend\View\Model\JsonModel;
use Application\Component\UserComponent;
use Application\Component\UserFacebookComponent;
use DateTime;

class TestaController extends AbstractActionController
{

    protected $em;

    protected $storage;

    protected $authservice;

    protected $userComponent;

    protected $userFacebookComponent;

    public function init()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            $this->userComponent = new UserComponent($this->em);
            $this->userFacebookComponent = new UserFacebookComponent($this->em);
        }
        return $this->em;
    }

    public function getSessionStorage()
    {
        if (! $this->storage) {
            $this->storage = $this->getServiceLocator()->get('Application\Model\MyAuthStorage');
        }
        
        return $this->storage;
    }

    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
        }
        return $this->authservice;
    }

    public function isAuthenticate()
    {
    	
        if ($user = $this->identity()) {
        	return true;
        } else {
        	return false;
        }
    }
    
    public function confirmAction()
    {
    	return new ViewModel();
    }

    public function feedAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "National Geographic Channel Channel Channel Channel",
            "image"=> "http://10.0.2.2/putmark/public/test_android/cosmos.jpg",
            "status"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "profilePic"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "timeStamp"=> "1403375851930",
            "url"=> null);
        return new JsonModel(array("feed"=>$feeds));
    }
	
	public function uploadPhotoAction()
    {//List marks of a photo given as parameter
		$message = array("code"=>0);
		try {
			$file = $this->imageUploader("file");
			if($file!=null && $file!="-1"){
				$message = array(
				'code'=>'success',
				'success'=>'image uploaded',
                'file' => $file
				);
			}else if($file!=null && $file!="-1"){
				$message = array(
				'code'=>'error',
                'error' => $file
				);
			}
		} catch (\Exception $e) {
            $message = array(
				'code'=>'error',
                'exception' => $e->getTraceAsString()
            );
        }
        return new JsonModel($message);
    }
	
	public function photoMarksAction()
    {//List marks of a photo given as parameter
		$marks = array();
		for($i=1; $i<=10; $i++)
		$marks[] = array(
			"id"=>$i,
			"value"=>10-$i,
			"userName"=> "Name of user ".$i,
            "userImage"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "description"=> "Comment of the mark here",
            "timestamp"=> "1403375851930",
            );
        return new JsonModel(array("marks"=>$marks));
    }
	
	
	public function markPhotoAction()
    {//Mark a photo and send back the result that can be
		$post = $this->request->getPost();
        $id = (int)$this->params()->fromPost('id');//The id of the photo to mark
		$user = $this->identity();
        $value = (int)$this->params()->fromPost('value');
        $description = $this->params()->fromPost('description');
		
		
		$mark = array(
			"id"=>$id,
			"value"=>$value,
			"userName"=> $user!=null?($user->firstname." ".$user->lastname):"No user",
            "userImage"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "description"=> $description,
            "timestamp"=> "1403375851930",
            );
        return new JsonModel(array("success"=>"mark published","mark"=>$mark));
    }

    public function albumsAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "My album long title ".$i,
            "image"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "nbPicts"=> 2*$i-2,
            "desc"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "timeStamp"=> "1403375851930",
            );
        return new JsonModel(array("albums"=>$feeds));
    }

	//Photos of an album given by it's id
    public function photosAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "My album long title ".$i,
            "image0"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "image"=> "http://10.0.2.2/putmark/public/test_android/picts/".$i.".png",
            "nb_marks"=> 2*$i-2,
            "desc"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "timestamp"=> "1403375851930",
            );
        return new JsonModel(array("photos"=>$feeds));
    }
	
	public function getuserAction()
    {
		$user = $this->identity();
		if($user!=null){
			$message = array(
				'success' => 'User connected',
				'uid'=>$user->uid,
				'firstname'=>$user->firstname,
				'lastname'=>$user->lastname,
				'photo'=>$user->picwithlogo==null?"http://10.0.2.2/putmark/public/test_android/user.png":$user->picwithlogo,
			);
		}else{
			$message = array(
				'error' => 'Please log in',
			);
		}
        return new JsonModel($message);
	}
	
	public function authAction()
    {
      
		$post = $this->request->getPost();
		/*if($this->request->isPost()) {
			var_dump($post);
			var_dump($this->request->getPost("email"));
			var_dump($this->params()->fromPost('email'));
			var_dump($post["email0"]);
		}*/
        $email = $this->params()->fromPost('email');
        $rememberMe = $this->getRequest()->getPost('remember_me');
        $password = $this->request->getPost('password');
		/*$message = array(
                'success' => $email,
				'uid'=>$password,
				'rememberMe'=>$rememberMe,
				'form'=>$this->request->getPost(),
            );
		return new JsonModel($message);*/
        //$this->init();
        
        //$this->getAuthService()->setStorage($this->getSessionStorage());
        
        $adapter = $this->getAuthService()->getAdapter();
        $adapter->setIdentityValue($email);
        $adapter->setCredentialValue($password);
        
        $authResult = $this->getAuthService()->authenticate();
        
        if ($authResult->isValid()) {
			$user = $this->identity();
            $message = array(
                'success' => 'Authentication successful',
				'uid'=>$user->uid,
				'firstname'=>$user->firstname,
				'lastname'=>$user->lastname,
				'photo'=>$user->picwithlogo==null?"http://10.0.2.2/putmark/public/test_android/user.png":$user->picwithlogo,
            );
            return new JsonModel($message);
        }
        $message = array(
            'error' => 'Your authentication credentials are not valid'
        );
        return new JsonModel($message);
    }
	
	public function logoutAction()
    {
        $me = $this->getServiceLocator()->get('ReverseOAuth2\Facebook');
        $me->clear();
        $this->getAuthService()->clearIdentity();
        $message = array(
                'success' => 'Logged out',
        ); 
		return new JsonModel($message);
        //$this->flashmessenger()->addMessage("You've been logged out");
        //return $this->redirect()->toRoute('home');
    }
 
}
